package com.example.shuiyin.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.shuiyin.entity.FileInfo;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface FileInfoMapper extends BaseMapper<FileInfo> {
    
    /**
     * 根据文件ID查询文件信息
     * 
     * @param fileId 文件ID
     * @return 文件信息
     */
    @Select("SELECT * FROM files WHERE file_id = #{fileId} AND status != 'DELETED'")
    FileInfo selectByFileId(@Param("fileId") String fileId);
    
    /**
     * 根据文件ID和用户ID查询文件信息
     * 
     * @param fileId 文件ID
     * @param userId 用户ID
     * @return 文件信息
     */
    @Select("SELECT * FROM files WHERE file_id = #{fileId} AND user_id = #{userId} AND status != 'DELETED'")
    FileInfo selectByFileIdAndUserId(@Param("fileId") String fileId, @Param("userId") Long userId);
    
    @Select("SELECT * FROM files WHERE user_id = #{userId} AND file_hash = #{fileHash} AND status = #{status} LIMIT 1")
    FileInfo selectByUserIdAndFileHashAndStatus(
            @Param("userId") Long userId, 
            @Param("fileHash") String fileHash, 
            @Param("status") String status);
    
    @Select("SELECT SUM(size) FROM files WHERE user_id = #{userId} AND status = 'ACTIVE'")
    Long selectTotalFileSize(@Param("userId") Long userId);
    
    @Delete("DELETE FROM files WHERE url LIKE CONCAT(#{prefix}, '%')")
    int deleteByPathPrefix(@Param("prefix") String prefix);
    
    @Select("SELECT * FROM files WHERE url LIKE CONCAT(#{prefix}, '%')")
    List<FileInfo> selectByPathPrefix(@Param("prefix") String prefix);
    
    @Update("UPDATE files SET status = 'DELETED', deleted_time = NOW() WHERE user_id = #{userId} AND status = 'ACTIVE' AND upload_time < DATE_SUB(NOW(), INTERVAL #{days} DAY)")
    int markOldFilesAsDeleted(@Param("userId") Long userId, @Param("days") int days);
    
    @Select("SELECT COUNT(*) FROM files WHERE user_id = #{userId} AND status = 'ACTIVE'")
    int countActiveFiles(@Param("userId") Long userId);
    
    @Select("SELECT * FROM files WHERE status = 'ACTIVE' AND upload_time < #{expiredTime}")
    List<FileInfo> selectExpiredFiles(@Param("expiredTime") java.time.LocalDateTime expiredTime);
} 